package com.zhuxin.events;

import com.google.gson.Gson;
import com.soecode.wxtools.api.IService;
import com.soecode.wxtools.api.WxConsts;
import com.soecode.wxtools.api.WxMessageHandler;
import com.soecode.wxtools.bean.KfSender;
import com.soecode.wxtools.bean.SenderContent;
import com.soecode.wxtools.bean.WxXmlMessage;
import com.soecode.wxtools.bean.WxXmlOutMessage;
import com.soecode.wxtools.exception.WxErrorException;
import com.zhuxin.common.UtilTools;
import com.zhuxin.medical.model.po.CommAppLog;
import com.zhuxin.medical.mvc.controller.WxMsg;
import org.springframework.beans.factory.annotation.Value;

import java.util.List;
import java.util.Map;

/**
 * Created by lzb on 2018/11/13.
 */
public class EventHandle extends BaseHandler implements WxMessageHandler {

    @Value("${wx.domainName.test}")
    private String domainName;//域名

    @Override
    public WxXmlOutMessage handle(WxXmlMessage wxMessage, Map<String, Object> map, IService iService) throws WxErrorException {
        WxXmlOutMessage xmlOutMsg = null;
        CommAppLog log=null;
        String msg="您好，首次使用请输入您销售系统的用户名.";
        if(UtilTools.isNullOrBlank(WxMsg.curruser.get().getUsername())){
            return WxXmlOutMessage.TEXT().content(msg).toUser(wxMessage.getFromUserName()).fromUser(wxMessage.getToUserName()).build();
        }
        switch (wxMessage.getEvent()){
            case "subscribe":
                msg=WxMsg.curruser.get().getUsername()+",欢迎回来。";
                xmlOutMsg = WxXmlOutMessage.TEXT().content(msg).toUser(wxMessage.getFromUserName()).fromUser(wxMessage.getToUserName()).build();
                break;
            case "SCAN":
                String uuid=wxMessage.getEventKey();
                log=new CommAppLog();
                log.setRecid(uuid);
                log=this.mysqlDao.queryVoByKey(log);
//                Map<String,String> param=new Gson().fromJson(wxMessage.getEventKey(),Map.class);
                Map<String,String> plans=new Gson().fromJson(log.getPlaninf(),Map.class);
                StringBuffer sb=new StringBuffer(WxMsg.curruser.get().getUsername());
                sb.append("，您好。\n\n当前待作废方案:\n");
                plans.forEach((k,v)->{
                    sb.append(k).append(",").append(v).append("\n");
                });
                sb.append("\n作废理由:\n").append(log.getReason()).append("\n\n");
                sb.append("<a href='")
                        .append("http://").append(domainName).append("/wxPage/WxCancelPlanInit?infoId=").append(log.getRecid())
                        .append("'>").append("点击查看详情").append("</a>");
//                sb.append("是否允许该操作?")
//                        .append("<a href=\"http://e22v638378.imwork.net\">是</a>")
//                        .append("               ")
//                        .append("<a href=\"http://e22v638378.imwork.net\">否</a>");
                xmlOutMsg = WxXmlOutMessage.TEXT().content(sb.toString()).toUser(wxMessage.getFromUserName()).fromUser(wxMessage.getToUserName()).build();
                break;
            case "CLICK":
                msg="不支持!";
                switch (wxMessage.getEventKey()){
                    case "zuofei":
                        if(WxMsg.curruser.get().getUsertype().intValue()==1){
                            msg="作为一个有权限的王者，直接去佣金前台作废方案吧。= =";
                            break;
                        }
                        Object o=this.checkUserStatus(wxMessage,map,iService);
                        if(o instanceof String)msg= (String) o;
                        else xmlOutMsg= (WxXmlOutMessage) o;
                        break;

                    case "list":
                        if(WxMsg.curruser.get().getUsertype().intValue()==1){
                            List<CommAppLog> list=this.mysqlDao.querySub("select * from commAppLog where status=2",CommAppLog.class);
                            StringBuffer ls=new StringBuffer();

                            list.forEach(l->{
                                String confirmUrl = "http://"+domainName+"/wxPage/WxCancelPlanInit?infoId="+l.getRecid();
                                System.out.println(confirmUrl);
                                ls.append(l.getOpername()+":")
                                        .append("<a href='"+confirmUrl+"'>详情</a>")
                                        .append("\n");
                            });
                            if(ls.length()==0)ls.append("无待审批方案.");
                            msg= ls.toString();
                        }else{
                            msg="无权执行此操作.";
                        }

//                        return WxXmlOutMessage.TEXT().content(ls.toString()).toUser(wxMessage.getFromUserName()).fromUser(wxMessage.getToUserName()).build();
                        break;
                }
                if(xmlOutMsg==null) {
                    KfSender sender = new KfSender();
                    sender.setTouser(wxMessage.getFromUserName());
                    sender.setMsgtype(WxConsts.MASS_MSG_TEXT);
                    sender.setText(new SenderContent.Text(msg));
                    sender.setCustomservice(new SenderContent.CustomService("kf2001@linyukeji007"));
                    iService.sendMessageByKf(sender);
                }
                xmlOutMsg = null;
                break;

            default:
                xmlOutMsg = WxXmlOutMessage.TEXT().content("不支持事件!!!").toUser(wxMessage.getFromUserName()).fromUser(wxMessage.getToUserName()).build();
                break;
        }
        return xmlOutMsg;
    }
}
